package com.example.controller;

import com.example.constants.Constants;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wen
 * @date 2021/8/17
 */
@RestController
@RequestMapping("ttl")
public class TestTTLController {
    @Resource
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("test/queue")
    public String send() {

        /**
         * 发送消息
         */
        for (int i = 0; i < 10; i++) {
            String str = "我是第 " + i + " 条消息\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS").format(new Date());
            rabbitTemplate.convertAndSend(Constants.MY_TTL_FANOUT_EXCHANGE, "", str);
            System.out.println("消息发送成功!\t" + str);
        }
        return "success";
    }

    @RequestMapping("test/msg")
    public String sendTTL() {

        /**
         * 发送消息
         */
        for (int i = 0; i < 10; i++) {
            String str = "我是第 " + i + " 条消息\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS").format(new Date());
            /**
             * 偶数使用队列的过期时间
             * 奇数使用自定义过期时间
             */
            if (i % 2 == 0) {
                rabbitTemplate.convertAndSend(Constants.MY_TTL_FANOUT_EXCHANGE, "", str);
            } else {
                rabbitTemplate.convertAndSend(Constants.MY_TTL_FANOUT_EXCHANGE, "", str, (message) -> {
                    message.getMessageProperties().setExpiration("10000");
                    return message;
                });
            }
            System.out.println("消息发送成功!\t" + str);
        }
        return "success";
    }
}
